<template>
  <div class="login-container">
    <div class="JPdom" ref="JPdom"></div>
    <div
      v-if="!notFound"
      class="login-center"
      ref="loginCenter"
      :style="{ backgroundImage: `url(${loginBgUrl})` }"
    >
      <div class="login-data" v-show="name == '登录'">
        <header>账户登录</header>
        <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          label-width="95px"
          size="large"
          label-position="top"
        >
          <el-form-item prop="phonenum" label="账号/手机号" class="text-item">
            <el-input
              size="large"
              placeholder="账号/手机号"
              name="phonenum"
              v-model="form.phonenum"
              prefix-icon="User"
              clearable
              :disabled="loginLoading"
              @keyup.enter="login(loginForm)"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码" class="text-item">
            <el-input
              size="large"
              placeholder="密码"
              name="password"
              type="password"
              show-password
              v-model="form.password"
              prefix-icon="Lock"
              clearable
              :disabled="loginLoading"
              @keyup.enter="login(loginForm)"
            >
            </el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12" class="col m-0 p-0">
              <el-button
                class="login-btn"
                type="primary"
                size="large"
                :loading="loginLoading"
                @click="login(loginForm)"
              >
                {{ loginLoading ? "登录中..." : "登录" }}
              </el-button>
            </el-col>
            <el-col :span="12" class="col m-0 p-0">
              <el-button
                class="forget-pwd"
                text
                size="large"
                @click="name = '忘记密码'"
                :disabled="loginLoading"
              >
                忘记密码
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 忘记密码 -->
      <div class="login-data" v-show="name == '忘记密码'">
        <header>忘记密码</header>
        <el-form
          ref="forgetref"
          :model="forget"
          label-width="95px"
          size="large"
          label-position="top"
        >
          <el-form-item class="text-item" label="手机号：" prop="phonenum">
            <el-input
              size="large"
              placeholder="请输入手机号"
              name="phonenum"
              v-model="forget.phonenum"
              prefix-icon="Phone"
              clearable
              :disabled="resetLoading"
            ></el-input>
          </el-form-item>
          <el-form-item class="text-item" label="验证码：" prop="yzm">
            <div class="row m-0">
              <div class="col p-0">
                <el-input
                  size="large"
                  placeholder="四位验证码"
                  v-model="forget.yzm"
                  prefix-icon="Message"
                  clearable
                  :disabled="resetLoading"
                ></el-input>
              </div>
              <div class="col">
                <el-button
                  style="margin-top: 0"
                  class="login-btn"
                  type="primary"
                  size="large"
                  @click.stop.prevent="sendCode"
                  :disabled="codeTime !== 60 || resetLoading"
                >
                  {{ codeTime == 60 ? "获取验证码" : `${codeTime}s` }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="text-item" label="新密码：" prop="password">
            <el-input
              size="large"
              placeholder="请输入新密码"
              name="newpassword"
              type="password"
              show-password
              v-model="forget.password"
              prefix-icon="Lock"
              clearable
              :disabled="resetLoading"
            ></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12" class="col m-0 p-0">
              <el-button
                class="login-btn"
                type="primary"
                size="large"
                :loading="resetLoading"
                @click="forgetpassword"
              >
                {{ resetLoading ? "修改中..." : "修改密码" }}
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button
                class="forget-pwd"
                text
                size="large"
                @click="name = '登录'"
                :disabled="resetLoading"
                >返回登录</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div v-else class="not-found">
      <div class="not-found-content">
        <el-icon size="48">
          <WarningFilled />
        </el-icon>
        <span>团队不存在</span>
        <p>请检查访问地址是否正确</p>
      </div>
    </div>
    <LoginFooter></LoginFooter>
  </div>
</template>

<script lang="ts" setup>
import { WarningFilled } from "@element-plus/icons-vue";
import { ElForm, ElMessage, FormInstance } from "element-plus";
import { Particle } from "jparticles";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncgetregistphoneVerificationCode,
  asynclogin,
  asyncresetpassword,
} from "../../api/index";
import { Storekey } from "../../interface";
import { isPhonenum } from "../../util/RegExp";
import LoginFooter from "./LoginFooter.vue";

const store = useStore(Storekey);
const router = useRouter();

// 状态管理
const name = ref("登录");
const loginLoading = ref(false);
const resetLoading = ref(false);
const codeTime = ref(60);
const notFound = ref(false);
const teamid = ref();
const loginBgUrl = ref(
  "https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/%E7%A0%81%E5%AE%A2%E8%A1%8C-admin-login.png"
);

// 表单引用
const loginForm = ref<FormInstance>();
const forgetref = ref<FormInstance>();
const JPdom = ref();
const loginCenter = ref();
const jpdata = ref<Particle>();

// 表单数据
const form = reactive({
  password: "",
  phonenum: "",
  teamid: "",
});

const forget = reactive({
  phonenum: "",
  password: "",
  yzm: "",
});

const rules = ref({
  phonenum: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      message: "手机号不合法",
      regexp: /^1[3456789]\d{9}$/,
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "change" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
});

// 登录逻辑
async function login(loginForm: FormInstance | undefined) {
  if (!loginForm || loginLoading.value) return;

  try {
    const valid = await loginForm.validate();
    //  || !teamid.value
    if (!valid) {
      console.log("表单验证失败,teamid=>", teamid.value);
      return;
    }

    loginLoading.value = true;
    const { phonenum, password } = form;

    await asynclogin({ ID: phonenum, password, teamid: teamid.value });
    await store.dispatch("actiononline");
    ElMessage.success("登录成功");

    const redirect = router.currentRoute.value.query.redirect as string;
    router.push(redirect || { name: "主页" });
  } catch (e: any) {
    console.log("catch login error=>", e);
    // ElMessage.error(String(e));
  } finally {
    loginLoading.value = false;
  }
}

// 发送验证码
async function sendCode() {
  if (codeTime.value !== 60 || resetLoading.value) return;

  const { phonenum } = forget;
  if (!isPhonenum.test(phonenum)) {
    ElMessage.error("请输入正确的手机号");
    return;
  }

  try {
    await asyncgetregistphoneVerificationCode(phonenum);
    ElMessage.success("验证码已发送");

    const timer = setInterval(() => {
      codeTime.value = codeTime.value - 1;
      if (codeTime.value == 0) {
        clearInterval(timer);
        codeTime.value = 60;
      }
    }, 1000);
  } catch (e: any) {
    ElMessage.error(String(e));
  }
}

// 重置密码
async function forgetpassword() {
  if (resetLoading.value) return;

  try {
    resetLoading.value = true;
    const { phonenum, password } = forget;
    await asyncresetpassword(forget);
    ElMessage.success("修改密码成功");

    // 自动填充登录表单
    form.phonenum = phonenum;
    form.password = password;
    name.value = "登录";
  } catch (e: any) {
    ElMessage.error(String(e));
  } finally {
    resetLoading.value = false;
  }
}

onMounted(() => {});
onUnmounted(() => {
  jpdata.value?.onDestroy();
  jpdata.value = undefined;
});
</script>

<style scoped>
/* 基础变量 */
.login-container {
  --login-text-color: #fff;
  --login-input-bg: rgba(255, 255, 255, 0);
  --login-border-color: rgba(255, 255, 255, 0.2);
  --login-transition: all 0.3s ease;

  min-height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;

  --el-radio-text-color: var(--login-text-color);
  --content-width: 932px;
}

/* 背景粒子 */
.JPdom {
  position: fixed;
  height: calc(100vh + 64px);
  width: 100vw;
  background-color: #444;
}

/* 登录主容器 */
.login-center {
  position: relative;
  width: 90%;
  max-width: var(--content-width);
  height: 540px;

  background-image: url(https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/guanwang/science2.png);
  background-repeat: no-repeat;
  background-size: cover;

  margin: auto;
  box-shadow: 0px 4.8px 14.4px rgba(0, 0, 0, 0.18),
    0px 25.6px 57.6px rgba(0, 0, 0, 0.22);
  border-radius: 8px;
  z-index: 1;
  display: flex;
  transition: var(--login-transition);
}

.login-center:hover {
  transform: translateY(-2px);
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.2), 0px 32px 64px rgba(0, 0, 0, 0.25);
}

/* 表单容器 */
.login-data {
  width: 442px;
  padding: 0 48px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: var(--login-text-color);
  --color-43: var(--login-text-color);
  animation: slideInLeft 0.5s ease-out;
}

.login-data header {
  font-weight: 700;
  font-size: 36px;
  margin-bottom: 30px;
  text-align: center;
}

/* 表单项样式 */
.text-item {
  margin-bottom: 24px;
  color: var(--login-text-color);
}

.text-item :deep(.el-form-item__label) {
  color: var(--login-text-color) !important;
  font-weight: 500;
}

.text-item :deep(.el-input__wrapper) {
  background: var(--login-input-bg);
  border: 1px solid var(--login-border-color);
  border-radius: 4px;
  transition: var(--login-transition);
}

.text-item :deep(.el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.4);
}

.text-item :deep(.el-input__wrapper.is-focus) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.6);
  box-shadow: 0 0 0 1px var(--login-border-color);
}

.text-item :deep(.el-input__inner) {
  color: var(--login-text-color);
}

.text-item :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.8);
}

.text-item :deep(.el-input__prefix) {
  color: rgba(255, 255, 255, 0.8);
}

/* 按钮样式 */
.login-btn {
  width: 148px;
  border-radius: 4px;
  margin-top: 10px;
  font-weight: 600;
  transition: var(--login-transition);
}

.login-btn:hover:not(.is-loading):not(.is-disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.forget-pwd {
  width: 148px;
  border-radius: 4px;
  margin-top: 10px;
  color: var(--login-text-color) !important;
  font-weight: 500;
  transition: var(--login-transition);
}

.forget-pwd:hover:not(.is-disabled) {
  transform: translateY(-1px);
}

/* 布局样式 */
.el-row {
  display: flex;
  flex-direction: row;
  gap: 20px;
}

.el-col {
  width: 50% !important;
  flex: 1;
}

.login-btn,
.forget-pwd {
  width: 100% !important;
  border-radius: 8px;
}

.row.m-0 {
  display: flex;
  gap: 20px;
  align-items: end;
}

.row.m-0 .col.p-0 {
  flex: 1;
  padding: 0 !important;
}

.row.m-0 .col {
  padding: 0 !important;
  flex-shrink: 0;
}

.row.m-0 .col .login-btn {
  height: 42px;
  font-size: 13px;
}

/* 错误页面样式 */
.not-found {
  position: relative;
  text-align: center;
  color: var(--sass-color-blue);
  font-weight: bolder;
  font-size: 50px;
  z-index: 1;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.not-found-content {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  padding: 40px;
  color: #e74c3c;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.not-found-content span {
  display: block;
  font-weight: 700;
  font-size: 24px;
  margin: 16px 0 8px;
}

.not-found-content p {
  color: #7f8c8d;
  margin: 0;
  font-size: 14px;
}

/* 动画效果 */
@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-12px);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 加载状态 */
.login-btn.is-loading,
.login-btn.is-disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .login-container {
    align-items: center;
    justify-content: flex-start;
    overflow-y: auto;
    min-height: 100vh;
    height: auto;
  }

  .login-center {
    width: 100%;
    max-width: 400px;
    height: auto;
    min-height: auto;
    display: block;
    overflow: hidden;
    flex-shrink: 0;
    background-image: url(https://cdn.hterobot.com/image/%E7%A0%81%E5%AE%A2%E8%A1%8C-admin-mobile-login.png) !important;
  }

  .login-data {
    width: 100%;
    padding: 32px 24px;
    background: rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(1px);
    border-radius: 8px;
    min-height: auto;
  }

  .login-data header {
    font-size: 24px;
    text-align: center;
    margin-bottom: 24px;
  }

  .text-item {
    margin-bottom: 22px;
  }

  .not-found-content {
    margin: 20px 16px;
    padding: 32px 24px;
    color: #ff4d4f;
    background: rgba(255, 255, 255, 0.9);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }
}

@media (max-width: 480px) {
  .login-container {
    min-height: 100vh;
    height: auto;
  }

  .login-center {
    width: calc(100% - 24px);
    background-image: url(https://cdn.hterobot.com/image/%E7%A0%81%E5%AE%A2%E8%A1%8C-admin-mobile-login.png) !important;
  }

  .login-data {
    padding: 24px 16px;
    min-height: auto;
  }

  .login-data header {
    font-size: 22px;
    margin-bottom: 20px;
  }

  .text-item {
    margin-bottom: 20px;
  }

  .login-btn,
  .forget-pwd {
    height: 44px;
    font-size: 14px;
  }
}

/* 防止页面滚动 */
@media (max-width: 768px) {
  body {
    overflow: auto;
    position: static;
    width: auto;
    height: auto;
  }
}
</style>

<style>
#app.acCoder .login-container .login-btn:hover {
  color: var(--login-text-color) !important;
  border-color: var(--login-text-color) !important;
  background-color: rgba(0, 0, 0, 0) !important;
  outline: 0;
}

#app.acCoder .login-container .el-button.is-text:not(.is-disabled):focus,
.el-button.is-text:not(.is-disabled):hover {
  background-color: transparent !important;
}

#app.acCoder .login-container .el-form-item__error {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

#app.acCoder .login-container .el-input__prefix {
  color: rgba(255, 255, 255, 0.7);
}

#app.acCoder .login-container .el-button.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
